package com.jessefyz.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jessefyz.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 *
 * @author Carlos
 */
@Component
public class MetaHandler implements MetaObjectHandler {


    private final String CREATE_TIME = "createTime";
    private final String CREATE_BY = "createBy";
    private final String UPDATE_TIME = "updateTime";
    private final String UPDATE_BY = "updateBy";

    private final String ADD_TIME = "addTime";

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter(CREATE_TIME)) {
            this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
        }
        if (metaObject.hasGetter(CREATE_BY)) {
            this.setFieldValByName(CREATE_BY, SecurityUtils.getUsername(), metaObject);
        }
        if (metaObject.hasGetter(ADD_TIME)) {
            this.setFieldValByName(ADD_TIME, new Date(), metaObject);
        }
        if (metaObject.hasGetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
        if (metaObject.hasGetter(UPDATE_BY)) {
            this.setFieldValByName(UPDATE_BY, SecurityUtils.getUsername(), metaObject);
        }
    }

    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
        if (metaObject.hasGetter(UPDATE_BY)) {
            this.setFieldValByName(UPDATE_BY, SecurityUtils.getUsername(), metaObject);
        }
    }

}
